package cn.tang.tframe.common.utils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by tanghc on 2015/11/16.
 */
public class LRUCache<K, V> extends LinkedHashMap<K, V> implements Map<K, V> {

	private static final long serialVersionUID = 3287465019378048110L;
	private static final float DEFAULT_LOADFACTOR = 0.75F;
	private static final int DEFAULT_CACHESIZE = 1 << 8;
	private final int cacheSize;

	public LRUCache() {
		this(DEFAULT_CACHESIZE);
	}

	public LRUCache(int cacheSize) {
		this(cacheSize, DEFAULT_LOADFACTOR);
	}

	public LRUCache(int cacheSize, float loadFactor) {
		super(cacheSize + (int) (cacheSize * (1.0F - loadFactor)) + 1, loadFactor);
		this.cacheSize = cacheSize;
	}

	@Override
	protected boolean removeEldestEntry(Entry<K, V> eldest) {
		return this.size() > cacheSize;
	}
}